package com.ruoyi.mall.app.controller;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.mall.app.config.WechatPayConfig;
import com.ruoyi.mall.app.service.DtsOrderService;
import com.ruoyi.mall.common.domain.DtsOrder;
import com.ruoyi.mall.common.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

@RestController
@RequestMapping("/api/index/payable")
public class DtsWxPay extends BaseController {

    @Autowired
    private DtsOrderService dtsOrderService;

    @Autowired
    private WechatPayConfig wechatPayConfig;

    @GetMapping("/pay")
    public AjaxResult pay(DtsOrder dtsOrder) {
        List<DtsOrder> list = dtsOrderService.selectOrderDetail(dtsOrder);
        if (list == null) {
            return error("订单已取消");
        }

        if (!list.get(0).getOrderStatus().equals("101")) {
            return error("订单已支付，请不要重复操作");
        }

        String nonceStr = CharUtils.getRandomString(32);
        Map<String, String> resultObj = new TreeMap<String, String>();
        try {
            Map<String, String> parame = new TreeMap<String, String>();
            parame.put("appid", wechatPayConfig.getAppId());
            // 商家账号。
            parame.put("mch_id", wechatPayConfig.getMchId());
            String randomStr = CharUtils.getRandomString(18).toUpperCase();
            // 随机字符串
            parame.put("nonce_str", randomStr);
            // 商户订单编号 (流水号)
            parame.put("out_trade_no", list.get(0).getOrderSn());
            Map orderGoodsParam = new HashMap();
            orderGoodsParam.put("order_id", list.get(0).getId());
            // 商品描述
            parame.put("body", "支付");

            // 支付金额
            // 微信支付提交的金额是不能带小数点的，且是以分为单位，如果是以元为单位要处理下金额，即先乘以100，再去小数点
            parame.put("total_fee", String.valueOf(list.get(0).getOrderPrice().multiply(new BigDecimal(100)).setScale(0, BigDecimal.ROUND_HALF_UP)));
            // 回调地址
            parame.put("notify_url", wechatPayConfig.getNotifyUrl());
            // 交易类型APP
            parame.put("trade_type", wechatPayConfig.getTradeType());
            // 开发者id
            parame.put("openid", "ost1p5C82-sADF_JamTcf46POCFA");

            String sign = WXPayUtil.generateSignature(parame, wechatPayConfig.getMchKey());
            // 数字签证
            parame.put("sign", sign);
            // 将map集合转换成XML
            String xml = WXPayUtil.mapToXml(parame);
            Map<String, Object> resultUn = XmlUtil.xmlStrToMap(WechatUtil.requestOnce(wechatPayConfig.getUniformorder(), xml));
            // 响应报文
            String return_code = MapUtils.getString("return_code", resultUn);
            String return_msg = MapUtils.getString("return_msg", resultUn);
            //
            if (return_code.equalsIgnoreCase("FAIL")) {
                return error("支付失败,失败信息是：" + return_msg);
            } else if (return_code.equalsIgnoreCase("SUCCESS")) {
                // 返回数据
                String result_code = MapUtils.getString("result_code", resultUn);
                String err_code_des = MapUtils.getString("err_code_des", resultUn);
                if (result_code.equalsIgnoreCase("FAIL")) {
                    return error("支付失败" + err_code_des);
                } else if (result_code.equalsIgnoreCase("SUCCESS")) {
                    String prepay_id = MapUtils.getString("prepay_id", resultUn);
                    // 先生成paySign 参考https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=7_7&index=5
                    resultObj.put("appId", wechatPayConfig.getAppId());
                    resultObj.put("timeStamp", DateUtils.timeToStr(System.currentTimeMillis() / 1000, DateUtils.DATE_TIME_PATTERN));
                    resultObj.put("nonceStr", nonceStr);
                    resultObj.put("package", "prepay_id=" + prepay_id);
                    resultObj.put("signType", "MD5");

                    // String paySign = WechatUtil.arraySign(resultObj, ResourceUtil.getConfigByName("wx.paySignKey"));
                    String packageSign = WXPayUtil.generateSignature(resultObj, wechatPayConfig.getMchKey());
                    resultObj.put("paySign", packageSign);
                    System.out.println("=============================支付签名paySign为：" + packageSign);
                    // 业务处理
                    // orderInfo.setPayId(prepay_id);
                    // 付款中
                    return success(resultObj);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return error("下单失败,error=" + e.getMessage());
        }
        return null;
    }
}
